package com.libraries.helper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.example.libraries.R;
import com.libraries.entities.UpdateInfo;
import com.libraries.progressbar.NumberProgressBar;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

/**
 * @author wellsa
 *
 * @date 2016-4-26
 */

@SuppressLint("NewApi")
public class UpdateManager implements OnClickListener {
	/* 下载中 */
	private static final int DOWNLOAD_ING = 1;
	/* 下载结束 */
	private static final int DOWNLOAD_SUCCESS = 2;
	private static final int DOWNLOAD_FAILED = -1;
	/* 下载保存路径 */
	private String downloadPath;
	private UpdateInfo updateInfo;
	/* 是否取消更新 */
	private boolean isCanceled;

	private Context mContext;
	private Dialog updateDialog;
	private View v_spilt;
	private View v_title;
	private TextView tv_title, tv_content;
	private NumberProgressBar progressBar;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			Logger.log(this, "handleMessage",msg);
			switch (msg.what) {
			// 正在下载
			case DOWNLOAD_ING:
				// 设置进度条位置
				progressBar.setProgress(msg.arg1);
				break;
			case DOWNLOAD_SUCCESS:
				updateDialog.dismiss();
				// 安装文件
				installApk();
				break;
			default:
				v_title.setVisibility(View.VISIBLE);
				tv_title.setText(R.string.update_failed);
				progressBar.setVisibility(View.GONE);
				v_spilt.setVisibility(View.GONE);
				btn_okay.setVisibility(View.GONE);
				btn_cancel.setText(R.string.do_cancel);
				tv_content.setVisibility(View.VISIBLE);
				tv_content.setText(updateInfo.getMsg());
				break;
			}
		};
	};
	private Button btn_okay;
	private Button btn_cancel;

	public UpdateManager(Context context) {
		this.mContext = context;

	}

	/**
	 * 显示软件更新对话框
	 */
	public void showDialog(UpdateInfo updateInfo) {
		this.isCanceled = false;
		this.updateInfo = updateInfo;
		// 构造对话框
		updateDialog = new Dialog(mContext, R.style.dialog);
		updateDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		updateDialog.setContentView(R.layout.update_layout);
		v_spilt = updateDialog.findViewById(R.id.v_spilt);
		v_title = updateDialog.findViewById(R.id.v_title);
		tv_title = (TextView) updateDialog.findViewById(R.id.tv_title);
		tv_content = (TextView) updateDialog.findViewById(R.id.tv_content);
		progressBar = (NumberProgressBar) updateDialog.findViewById(R.id.pb_progress);
		btn_okay = (Button) updateDialog.findViewById(R.id.btn_okay);
		btn_okay.setOnClickListener(this);
		btn_cancel = (Button) updateDialog.findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(this);

		switch (updateInfo.getCode()) {
		case 0:
			v_title.setVisibility(View.GONE);
			v_spilt.setVisibility(View.GONE);
			btn_okay.setVisibility(View.GONE);
			btn_cancel.setText(R.string.do_okay);
			tv_content.setText(R.string.update_newest);
			break;
		case 1:
			tv_title.setText(R.string.update_discover);
			tv_content.setText(updateInfo.getMsg());
			break;
		default:
			tv_title.setText(R.string.update_failed);
			v_spilt.setVisibility(View.GONE);
			btn_okay.setVisibility(View.GONE);
			btn_cancel.setText(R.string.do_okay);
			tv_content.setText(updateInfo.getMsg());
			break;
		}
		windowDeploy();
		updateDialog.show();
	}

	@SuppressWarnings("deprecation")
	public void windowDeploy() {
		Window window = updateDialog.getWindow(); // 得到对话框
		window.setBackgroundDrawableResource(com.example.libraries.R.color.transparent);
		WindowManager.LayoutParams wl = window.getAttributes();
		wl.type = WindowManager.LayoutParams.TYPE_APPLICATION;
		wl.gravity = Gravity.CENTER;
		wl.dimAmount = 0f;
		WindowManager m = window.getWindowManager();
		Display d = m.getDefaultDisplay(); // 为获取屏幕宽、高
		wl.width = d.getWidth();
		wl.height = d.getHeight();
		window.setAttributes(wl);
	}

	/**
	 * 下载文件线程
	 * 
	 */
	private class downloadThread extends Thread {

		@Override
		public void run() {
			try {
				// 判断SD卡是否存在，并且是否具有读写权限
				if (DeviceHelper.isMountting()) {
					// 获得存储卡的路径
					String dirPath = FileHelper.getDiskCachePath("download");
					String fileName = FileHelper.getFileName(".apk");
					downloadPath = dirPath + File.separator + fileName;
					URL url = new URL(updateInfo.getUrl());
					// 创建连接
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					conn.connect();
					// 获取文件大小
					int length = conn.getContentLength();
					Logger.log(this, "run file size", length);
					// 创建输入流
					InputStream is = conn.getInputStream();

					File file = new File(dirPath);
					// 判断文件目录是否存在
					if (!file.exists()) {
						file.mkdir();
					}
					File apkFile = new File(downloadPath);
					FileOutputStream fos = new FileOutputStream(apkFile);
					int count = 0;
					// 缓存
					byte buf[] = new byte[1024];
					// 写入到文件中
					do {
						int numread = is.read(buf);
						count += numread;
						// 计算进度条位置
						int progress = (int) (((float) count / length) * 100);
						// 更新进度
						Message msg = Message.obtain();
						Logger.log(this, "run rece size",progress,numread);
						if (numread <= 0) {
							msg.what = DOWNLOAD_SUCCESS;
							// 下载完成
							isCanceled=true;
							mHandler.sendMessage(msg);
							break;
						}
						else{
							msg.what = DOWNLOAD_ING;
							msg.arg1 = progress;
							mHandler.sendMessage(msg);
						}
						// 写入文件
						fos.write(buf, 0, numread);
					} while (!isCanceled);// 点击取消就停止下载.
					fos.close();
					is.close();
				} else {
					downloadFaild("存储设备未加载!");
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
				downloadFaild(e.getMessage());
				Logger.log(this, "run MalformedURLException", e);
			} catch (IOException e) {
				e.printStackTrace();
				downloadFaild(e.getMessage());
				Logger.log(this, "run IOException", e);
			}
		}
	};

	private void downloadFaild(String reason) {
		updateInfo.setMsg(reason);
		mHandler.sendEmptyMessage(DOWNLOAD_FAILED);
	}

	/**
	 * 安装APK文件
	 */
	private void installApk() {
		File apkfile = new File(downloadPath);
		if (!apkfile.exists()) {
			return;
		}
		// 通过Intent安装APK文件
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		mContext.startActivity(i);
	}

	@Override
	public void onClick(View v) {
		int vid = v.getId();
		if (vid == R.id.btn_okay) {// 确定更新
			tv_title.setText(R.string.update_loading);
			tv_content.setVisibility(View.GONE);
			progressBar.setVisibility(View.VISIBLE);
			v_spilt.setVisibility(View.GONE);
			btn_okay.setVisibility(View.GONE);
			btn_cancel.setText(R.string.do_cancel);
			new downloadThread().start();
		} else if (vid == R.id.btn_cancel) {
			updateDialog.dismiss();
			isCanceled = true;
		}
	}

}
